package cn.stylefeng.gen.modular.controller;

import cn.hutool.core.util.StrUtil;
import cn.stylefeng.gen.core.DbUtil;
import cn.stylefeng.gen.core.JsonApiUtil;
import cn.stylefeng.gen.core.page.LayuiPageFactory;
import cn.stylefeng.gen.modular.model.DatabaseInfo;
import cn.stylefeng.gen.modular.model.SuccessResponseData;
import cn.stylefeng.gen.modular.model.TableFieldData;
import cn.stylefeng.gen.modular.repository.DatabaseInfoRepository;
import cn.stylefeng.guns.generator.core.generator.param.ContextParam;
import cn.stylefeng.guns.generator.modular.guns.GunsExecutor;
import cn.stylefeng.guns.generator.modular.restful.mybatisplus.param.MpParam;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.generator.config.po.TableField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 代码生成控制器
 *
 * @author fengshuonan
 * @date 2019-01-30-2:39 PM
 */
@Controller
@RequestMapping("/db")
public class DatabaseController {

    @Autowired
    private DatabaseInfoRepository databaseInfoRepository;

    /**
     * 数据库管理主页
     *
     * @author fengshuonan
     * @Date 2019/1/30 2:49 PM
     */
    @RequestMapping("")
    public String index() {
        return "/db.html";
    }

    /**
     * 新增页面
     *
     * @author fengshuonan
     * @Date 2019-01-11
     */
    @RequestMapping("/add")
    public String add() {
        return "/db_add.html";
    }

    /**
     * 新增
     *
     * @author fengshuonan
     * @Date 2019-01-11
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public Object addItem(DatabaseInfo databaseInfo) {
        this.databaseInfoRepository.save(databaseInfo);
        return new SuccessResponseData();
    }

    /**
     * 删除
     *
     * @author fengshuonan
     * @Date 2019-01-11
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(Long dbId) {
        this.databaseInfoRepository.deleteById(dbId);
        return new SuccessResponseData();
    }

    /**
     * 获取数据源列表
     *
     * @author fengshuonan
     * @Date 2019/1/30 2:49 PM
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object list() {
        List<DatabaseInfo> all = databaseInfoRepository.findAll();

        Page<DatabaseInfo> objectPage = new Page<>();
        objectPage.setRecords(all);

        return LayuiPageFactory.createPageInfo(objectPage);
    }

    /**
     * 获取某个数据源下的所有表
     *
     * @author fengshuonan
     * @Date 2019/1/30 2:49 PM
     */
    @RequestMapping("/tableList")
    @ResponseBody
    public Object tableList(Long dbId) {
        try {
            Optional<DatabaseInfo> byId = databaseInfoRepository.findById(dbId);
            DatabaseInfo databaseInfo = byId.get();
            List<Map<String, Object>> maps = DbUtil.selectTables(databaseInfo);
            Page<Map<String, Object>> objectPage = new Page<>();
            objectPage.setRecords(maps);
            return LayuiPageFactory.createPageInfo(objectPage);
        } catch (Exception e) {
            Page<Map<String, Object>> objectPage = new Page<>();
            return LayuiPageFactory.createPageInfo(objectPage);
        }
    }


    /**
     * 获取表中的字段信息
     *
     * @author yuelinbo
     * @date 2019/2/18 8:46
     **/
    @RequestMapping(value = "/tableFields")
    @ResponseBody
    public Object tableFields(String author, String proPackage, String removePrefix,
                              Long dataSourceId, String tables) {
        try {
            tables = tables.substring(3);

            String[] tableArray = tables.split("CAT");


            //获取数据源信息
            Optional<DatabaseInfo> dbInfo = this.databaseInfoRepository.findById(dataSourceId);

            DatabaseInfo databaseInfo = dbInfo.get();

            ContextParam contextParam = new ContextParam();
            contextParam.setAuthor(author);
            contextParam.setProPackage(proPackage);
            contextParam.setJdbcDriver(databaseInfo.getJdbcDriver());
            contextParam.setJdbcUserName(databaseInfo.getUserName());
            contextParam.setJdbcPassword(databaseInfo.getPassword());
            contextParam.setJdbcUrl(databaseInfo.getJdbcUrl());

            MpParam mpContextParam = new MpParam();
            mpContextParam.setGeneratorInterface(true);
            mpContextParam.setIncludeTables(tableArray);

            if (StrUtil.isNotEmpty(removePrefix)) {
                mpContextParam.setRemoveTablePrefix(new String[]{removePrefix});
            }

            //代码生成contextParam
            List<TableField> tableFields = GunsExecutor.executorTableFields(contextParam, mpContextParam);

            Page<TableField> objectPage = new Page<>();
            objectPage.setRecords(tableFields);
            return LayuiPageFactory.createPageInfo(objectPage);
        } catch (Exception e) {
            Page<Map<String, Object>> objectPage = new Page<>();
            return LayuiPageFactory.createPageInfo(objectPage);
        }

    }


    @RequestMapping("/buildApiJson")
    @ResponseBody
    public JSONObject buildApiJson(@RequestParam String apiJson) {


        List<TableFieldData> fieldInfos = JSONArray.parseArray(apiJson, TableFieldData.class);

        JSONObject jsonObject = JsonApiUtil.packJson(fieldInfos);


        return jsonObject;
    }

}
